/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.Almacen;

import gui.General.Main;
import java.awt.Color;
import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author César
 */
public class Kardex extends javax.swing.JInternalFrame {

    /**
     * Creates new form Kardex
     */
    
    TableModel tb;
    List<Controlador.Bean.Almacen.Kardex> datos;
    int numrow = 0;
    
    public Kardex() {
        initComponents();
        initComp();
        
    }
    
    
    public void initComp(){
        tb = new TableModel();
        datos = Controlador.Service.Almacen.GestionAlmacenes.obtenerKardex();
        asignarData();
        tblKardex.setModel(tb);
        createBorder(tb);
        TableColumnModel tcm = tblKardex.getColumnModel();
	for(int it = 0; it < tcm.getColumnCount(); it++){
		tcm.getColumn(it).setCellRenderer(jTableCellRenderer);
	}
    }

    private static Kardex mynp = null;

    public static Kardex getInstance() {
        if (mynp == null) {
            mynp = new Kardex();
            Main.getDesktop().add(mynp);
            mynp.setVisible(true);
            mynp.toFront();
        } else {
            if (mynp.isClosed() || !mynp.isVisible()) {
                mynp = new Kardex();
                Main.getDesktop().add(mynp);
                mynp.toFront();
                mynp.setVisible(true);
            } else {
                mynp.toFront();
            }
        }

        return mynp;
    } 
    
    
    
    
    public void asignarData(){
        String idProducto = "";
        numrow = 0;
        for(int i=0; i<datos.size(); i++){
            if(!idProducto.equals(datos.get(i).getIdProducto())){
                numrow++;
                idProducto = datos.get(i).getIdProducto();
            }
        }
        tb.data = new Object[numrow][tb.columnNames.length];
        idProducto = "";
        int row = 0;
        ArrayList<String> almacenes = new ArrayList<>(); 
        ArrayList<String> cantidad = new ArrayList<>();
        ArrayList<String> total = new ArrayList<>(); 
        for(int i=0; i<datos.size(); i++){
            if(!idProducto.equals(datos.get(i).getIdProducto())){
                if(!almacenes.isEmpty()){
                    tb.data[row][5] = almacenes.toArray();
                    tb.data[row][6] = cantidad.toArray();
                    tb.data[row][7] = total.toArray();
                    almacenes = new ArrayList<>();
                    cantidad = new ArrayList<>();
                    total = new ArrayList<>();
                    row++;
                }
                tb.data[row][0] = datos.get(i).getIdProducto();
                tb.data[row][1] = datos.get(i).getNombre();
                tb.data[row][2] = datos.get(i).getCantidadTotal();
                tb.data[row][3] = datos.get(i).getPreciobase();
                tb.data[row][4] = datos.get(i).getCantidadTotal()*datos.get(i).getPreciobase();
                almacenes.add(datos.get(i).getNombreAlmacen());
                cantidad.add(String.valueOf(datos.get(i).getCantidadAlmacen()));
                total.add(String.valueOf(datos.get(i).getCantidadAlmacen()*datos.get(i).getPreciobase()));
                idProducto = datos.get(i).getIdProducto();
            }else{
                almacenes.add(datos.get(i).getNombreAlmacen());
                cantidad.add(String.valueOf(datos.get(i).getCantidadAlmacen()));
                total.add(String.valueOf(datos.get(i).getCantidadAlmacen()*datos.get(i).getPreciobase()));
            }
            tb.data[row][5] = almacenes.toArray();
            tb.data[row][6] = cantidad.toArray();
            tb.data[row][7] = total.toArray();
        }
    }
     
    class TableModel extends AbstractTableModel{
              
        //Two arrays used for the table data
        String[] columnNames = {"Código", "Nombre", "Cantidas Total" , "Precio Unitario", "Precio Total", "Almacen"
                        , "Cantidad", "Precio"};
        String idProducto = "";       
        Object[][] data;
        
        
               
        @Override
        public int getRowCount()
        {
            return numrow;
        }
        
        @Override
        public int getColumnCount()            
        {
            return columnNames.length;
        }
        
        @Override
        public Object getValueAt(int row, int column)
        {           
            return data[row][column];
        }
        
        //Used by the JTable object to set the column names
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        //Used by the JTable object to render different
        //functionality based on the data type
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
        
        @Override
        public boolean isCellEditable(int row, int column)
        {
           return false;
        }
        
        public void actualizarTabla(){
            asignarData();
            fireTableDataChanged();
        }
        
    }
    
    TableCellRenderer jTableCellRenderer = new TableCellRenderer() {
	/* These are necessary variables to store the row's height */
	private int minHeight = -1;
	private int currHeight = -1;
	/* Magic Happens */
        @Override
	public Component getTableCellRendererComponent(JTable table,
	Object value, boolean  isSelected, boolean hasFocus,
	int row, int column) {
		/* If what we're displaying isn't an array of values we
		return the normal renderer*/
		if(!value.getClass().isArray()){
			return table.getDefaultRenderer( 
			value.getClass()).getTableCellRendererComponent(
			table, value, isSelected, hasFocus,row, column);
		}
		else{
			final Object[] passed = (Object[])value;
			/* We calculate the row's height to display data
			* THis is not complete and has some bugs that
			* will be analyzed in further articles */
			if(minHeight == -1){
				minHeight = table.getRowHeight();
			}
			
			if(currHeight != passed.length*minHeight){
				currHeight = passed.length * minHeight;
				table.setRowHeight(row,currHeight);
			}
			/* We create the table that will hold the multivalue
			*fields and that will be embedded in the main table */
			return new JTable(
				new AbstractTableModel() {
                                @Override
				public int getColumnCount() {
					return 1;
				}
                                @Override
				public int getRowCount() {
					return passed.length;
				}
                                @Override
				public Object getValueAt(int rowIndex, int columnIndex) {
					return passed[rowIndex];
				}
                                @Override
				public boolean isCellEditable(int row, int col){ return true; }
			});
		}
	}
	};

    private JComponent createBorder(TableModel model)
	{

		JTable table = new JTable( model )
		{
			private Border outside = new MatteBorder(1, 0, 1, 0, Color.RED);
			private Border inside = new EmptyBorder(0, 1, 0, 1);
			private Border highlight = new CompoundBorder(outside, inside);

			public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
			{
				Component c = super.prepareRenderer(renderer, row, column);
				JComponent jc = (JComponent)c;

				// Add a border to the selected row

				if (isRowSelected(row))
					jc.setBorder( highlight );

				return c;
			}
		};

		table.setPreferredScrollableViewportSize(table.getPreferredSize());
		table.changeSelection(0, 0, false, false);
		return new JScrollPane( table );
	}
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblKardex = new javax.swing.JTable();

        setClosable(true);
        setMaximumSize(new java.awt.Dimension(800, 600));
        setMinimumSize(new java.awt.Dimension(800, 600));
        setPreferredSize(new java.awt.Dimension(800, 600));

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jPanel1.setLayout(new java.awt.BorderLayout());

        tblKardex.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tblKardex);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 764, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(129, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblKardex;
    // End of variables declaration//GEN-END:variables
}
